package com.chenxi.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

public class CopyUtil {
    public static void CopyBean(Object source,Object dest) {
        BeanInfo sourceBean = null;
        BeanInfo destBean = null;
        try {
            sourceBean = Introspector.getBeanInfo(source.getClass(),Object.class);
            destBean = Introspector.getBeanInfo(dest.getClass(),Object.class);
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        PropertyDescriptor[] sourceProperties = sourceBean.getPropertyDescriptors();
        PropertyDescriptor[] destProperties = destBean.getPropertyDescriptors();
        for (PropertyDescriptor sourceProperty : sourceProperties) {
            for (PropertyDescriptor destProperty : destProperties) {
                if (sourceProperty.getName().equals(destProperty.getName())){
                    try {
                        destProperty.getWriteMethod().invoke(dest,sourceProperty.getReadMethod().invoke(source));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    }
}
